﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Compression;
using System.IO;

namespace MyServer.Common
{
    public sealed class GZipDataCompressor : DataCompressorBase
    {

        private object ZipLockObj = new object();
        private object UnZipLockObj = new object();

        //private byte[] ReadAllByte(GZipStream Stream)
        //{
        //    List<byte> Buffer = new List<byte>();
        //    while(true)
        //    {
        //        int Data = Stream.ReadByte();
        //        if (Data == -1)
        //            break;
        //        else
        //            Buffer.Add((byte)Data);
        //    }
        //    return Buffer.ToArray();
        //}

        public override byte[] Compress(byte[] Source)
        {
            lock (ZipLockObj)
            {
                List<byte> DataList = new List<byte>();
                MemoryStream CompressStream = new MemoryStream();
                GZipStream GzipStream = new GZipStream(CompressStream, CompressionMode.Compress);
                GzipStream.Write(Source, 0, Source.Count());
                GzipStream.Flush();
                GzipStream.Close();
                byte[] Data = CompressStream.ToArray();
                CompressStream.Close();
                if (Data.Count() >= Source.Count())
                {
                    DataList.Add(0);
                    DataList.AddRange(Source);
                }
                else
                {
                    DataList.Add(1);
                    DataList.AddRange(Data);
                }               
                return DataList.ToArray();
            }
        }

        public override byte[] DeCompress(byte[] Source)
        {
            lock (UnZipLockObj)
            {
                byte[] Data;
                if (Source[0] == 1)
                {
                    MemoryStream SourceStream = new MemoryStream(Source.Skip(1).ToArray());
                    MemoryStream BufferStream = new MemoryStream();
                    GZipStream GzipStream = new GZipStream(SourceStream, CompressionMode.Decompress);
                    GzipStream.CopyTo(BufferStream);
                    GzipStream.Close();
                    Data = BufferStream.ToArray();
                    SourceStream.Close();
                }
                else
                {
                    Data=Source.Skip(1).ToArray();
                }
                return Data;
            }
        }

    }
}
